class Solution {
    public String reverseOnlyLetters(String s) {
        if (s.length() <= 1) return s;
        return byDoublePointer(s);
    }

    private String byStack(String s) {
        Deque<Character> stack = new LinkedList<>();
        for (char c : s.toCharArray()) {
            if (Character.isLetter(c)) {
                stack.push(c);
            }
        }
        StringBuilder ans = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (Character.isLetter(c)) {
                ans.append(stack.pop());
            } else {
                ans.append(c);
            }
        }
        return ans.toString();
    }

    private String byDoublePointer(String s) {
        char[] charOfS = s.toCharArray();
        for (int i = 0, j = charOfS.length - 1; i < j; i++, j--) {
            if (!Character.isLetter(charOfS[i])) {
                j++;
                continue;
            }
            if (!Character.isLetter(charOfS[j])) {
                i--;
                continue;
            }
            char tmp = charOfS[i];
            charOfS[i] = charOfS[j];
            charOfS[j] = tmp;
        }
        return new String(charOfS);
    }
}
